package com.atguigu.day07;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;

public class Flink10_KeyedState_ListState {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);


        //3.将数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //4.将相同id的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = waterSensorStream.keyBy("id");


        //5.针对每个传感器需要统计最高的三个水位值
        keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {

            //TODO 1.定义状态
            private ListState<Integer> listState;


            @Override
            public void open(Configuration parameters) throws Exception {
                //TODO 初始化状态
                listState = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("listState", Integer.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //1.先判断状态中数据个数是否超过3
                Iterable<Integer> top3VcStateIter = listState.get();

                ArrayList<Integer> top3VcStateList = new ArrayList<>();

                //2.判断有多少个元素
                if (top3VcStateIter.spliterator().estimateSize()!=3){
                    //如果没有三个元素，则直接把数据放到list集合中
                    listState.add(value.getVc());
                    out.collect(listState.get().toString());
                }else {
                    //证明已经有最高的三个水位了，那么将三个最高的水位取出来
                    for (Integer integer : top3VcStateIter) {
                        top3VcStateList.add(integer);
                    }
                    //3.将当前的水位也放入list集合中做排序
                    top3VcStateList.add(value.getVc());
                    //4.对集合中的数据做排序
                    top3VcStateList.sort(new Comparator<Integer>() {
                        @Override
                        public int compare(Integer o1, Integer o2) {
                            return o2-o1;
                        }
                    });

                    //将最小的水位移除掉
                    top3VcStateList.remove(3);

                    //将list集合中最高的三个水位更新到状态中
                    listState.update(top3VcStateList);

                    out.collect(top3VcStateList.toString());
                }





            }
        }).print();

        env.execute();


    }
}
